<?php

/**
 * Created by PhpStorm.
 * User: yuchong
 * Date: 2015/2/4
 * Time: 9:53
 */

class Member_login_log_model extends MY_Model {

    protected $maxfailedcount = 3;
    protected $lockedhours = 1;

    public function __construct() {
        parent::__construct();
        $this->_table = "db_member_login_log";

    }

    /**
    *   添加记录
     */
    public function add($data) {
        $data = $this->filter_array( $data, array("username", "succeed" ) );
        return $this->insert( $data );
    }

    /**
    *   删除记录
     */
    public function del($post) {
        $where = array();
        if(!empty( $post['date'] )) {
            $where[] = " `time` < '" . strtotime( $post['date'] ) . "'";
        }
        if(!empty( $post['username'] )) {
            $where[] = "`username`='" . $post['username'] . "'";
        }
        if(!empty( $post['ip'] )) {
            $where[] = "`ip`='" . $post['ip'] . "'";
        }
        if(isset( $post['succeed'] ) && is_numeric( $post['succeed'] )) {
            $where[] = "`succeed`=" . intval( $post['succeed'] );
        }
        if(!empty( $where )) {
            $where = implode( " AND ", $where );
        }
        return $this->delete( $where );
    }

    /**
    *   需要分页的记录查询
     */
    public function page($username = NULL, $ip = NULL, $succeed = NULL, $mintime = NULL, $maxtime = NULL, $order = "`logid` DESC", $page = 1, $limit = 20) {
        if($username) {
            $this->db->where('username', $username);
        }
        if($ip) {
            $this->db->where('ip', $ip);
        }
        if($succeed != NULL) {
            $this->db->where('succeed', $succeed);
        }
        if($mintime) {
            $this->db->where('time >=', $mintime);
        }
        if($maxtime) {
            $this->db->where('time <=', $maxtime);
        }
        $this->db->order_by($order);

        $key = md5(microtime().'5tgame');
        $db[$key] = clone($this->db);
        $data['total'] = $db[$key]->count_all_results();

        $this->db->limit($limit, ($page - 1) * $limit);
        $data['result'] = $this->db->get()->result_array();
        if ($data) {
            return $data;
        }
        return false;
    }

    /**
    *   记录条数
     */
    public function total() {
        return $this->totals;
    }

    /**
    *   避免用户刷屏
     */
    public function valid($username) {
        $time = TIME - $this->lockedhours * 3600;
        $this->db->where('username', $username);
        $this->db->where('ip', IP);
        $this->db->where('time >', $time);
        $count = $this->db->count_all_results($this->_table);
        return $count <= $this->maxfailedcount ? true : false;
    }



}